import { getLocal } from '@/utils/local'
import store from '../store'
import * as types from '@/store/action-types'

class WS {
    constructor(config = {}) {
        this.url = config.url || 'vue.zhufengpeixun.cn';
        this.port = config.port || 80;
        this.protocol = config.protocol || 'ws';
        this.time = config.time || 30 * 1000;
        this.ws = null;
    }
    onOpen = () => {
        this.ws.send(JSON.stringify({
            type: 'auth',
            data: getLocal('token')
        }))
    }
    onMessage = (e) => {
        let { type, data } = JSON.parse(e.data);
        switch (type) {
            case 'noAuth':
                console.log('没有权限');
                break;
            case 'heartCheck':
                this.checkServer(); //触发检查服务器的方法，为了防止断线
                this.ws.send(JSON.stringify({ type: 'heartCheck' }));
                break;
            default: //默认情况下时提交消息
                store.commit(types.SET_MESSAGE, data);
        }
    }
    onError = () => {
        setTimeout(() => {
            this.create();
        }, 1000)
    }
    onClose = () => {
        this.ws.close();
    }
    create() {
        this.ws = new WebSocket(`${this.protocol}://${this.url}:${this.port}`);
        this.ws.onopen = this.onOpen;
        this.ws.onmessage = this.onMessage;
        this.ws.onclose = this.onClose;
        this.ws.onerror = this.onError;
    }
    checkServer() {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {

        }, this.time + 1000)
    }
    send = (msg) => {
        this.ws.send(JSON.stringify(msg));
    }
}
export default WS;